<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
	<title>Promise testDemo</title>
	<style type="text/css">
	* {
		padding: 0;
		margin: 0;
	}
	 
</style>
</head>
<body>
	<h1>aaaa</h1>
	<div id="box">
	    <h2>第九章 闭包与作用域</h2>
	    <button>收藏课程</button>
	  </div>
</body>
<script src="index.js"></script>
<script type="text/javascript">
function ajax(url) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.send();
    xhr.onload = function() {

      if (this.status == 200) {
        try{
          resolve(JSON.parse(this.response));
        } catch(err) {
          reject(err);
        }
      } else {
        reject(this);
      }
    };
  });
}

function query(name) {
  const cache = query.cache || (query.cache = new Map())
  if(cache.has(name)) {
    console.log('走了缓存')
    return Promise.resolve(cache.get(name))
  } else {
    var url = `http://localhost/ajax/ajax3.php?type=query&t=0&name=${name}`;
    return ajax(url).then(response => {
      cache.set(name, response)
      console.log('---------没走缓存2--------------\n')
      return response
    })
  }

}

var type = 1  

if(type) {
  query('向军').then(response => {
    console.log('then then')
    
    console.log(response)
  })
  setTimeout(() => {
    console.log('放在setTimeout里面')
    query('向军').then(response => {
      console.log(response)
    })

    // query('向军').then(response => {
    //   console.log(response)
    // }) 
  }, 100)
} else {
  query("向军").then(response => {
    console.log(response);
  });
  setTimeout(() => {
    query("向军").then(response => {
      console.log(response);
    });
  }, 1000);
}





</script>
</html>